﻿using HZY.Framework.DependencyInjection;
using IoTClient.Enums;
using Long.BLL;
using Long.Helper;
using Mapster;
using MiniExcelLibs;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Long.SpraySCADA
{
    public partial class PageRecipeManage : UIPage, ISingletonSelfDependency
    {
        private readonly RecipeManager _recipeManager;
        public PageRecipeManage(RecipeManager recipeManager)
        {
            InitializeComponent();
            this._recipeManager = recipeManager;
            this.dgv_Recipe.AutoGenerateColumns = false;
            this.dgv_Recipe.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            this.Load += PageRecipeManage_Load;
        }

        private async void PageRecipeManage_Load(object? sender, EventArgs e)
        {
            await LoadRecipe();

        }

        /// <summary>
        /// 加载出所有 配方
        /// </summary>
        /// <returns></returns>
        private async Task LoadRecipe()
        {
            BaseResult<RecipeQuaeryResultDto> res = await _recipeManager.GetRecipeListAsyncManager();
            if (res.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                this.dgv_Recipe.DataSource = null;
                this.dgv_Recipe.DataSource = res.Data;
            }
            else
            {
                LogExtension.ShowMessage(res.Msg, Microsoft.Extensions.Logging.LogLevel.Error);
            }
        }

        private async void btn_AddRecipe_Click(object sender, EventArgs e)
        {
            if (this.txt_ProductType.Text.IsNullOrEmpty())
            {
                UIMessageTip.ShowWarning("请输入产品型号");
                return;
            }

            RecipeAddDto addDto = new RecipeAddDto()
            {
                产品类型 = this.txt_ProductType.Text
            };
            foreach (var item in this.uiTitlePanel1.Controls)
            {
                if (item is UserSetValue usv)
                {
                    //通过自定义控件属性 VariableName ，反射至addDto
                    //string text = usv.VariableName;
                    addDto.GetType().GetProperty(usv.VariableName).SetValue(addDto, usv.VarValue);
                }
            }
            BaseResult res = await _recipeManager.AddRecipeAsyncManager(addDto);
            if (res.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                UIMessageTip.ShowOk("配方添加成功");
                await LoadRecipe();
            }
            else
            {
                UIMessageTip.ShowError(res.Msg);
                LogExtension.ShowMessage(res.Msg, Microsoft.Extensions.Logging.LogLevel.Error);
            }
        }

        private async void btn_DelRecipe_Click(object sender, EventArgs e)
        {
            if (this.dgv_Recipe.CurrentRow == null)
            {
                UIMessageTip.ShowWarning("请选择要删除的配方");
                return;
            }
            int ID = this.dgv_Recipe.CurrentRow.Cells["Id"].Value.ToString().ToInt();
            BaseResult res = await _recipeManager.DeleteRecipeAsyncManager(new RecipeDeleteDto() { Id = ID });
            if (res.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                UIMessageTip.ShowOk("配方删除成功");
                await LoadRecipe();
            }
            else
            {
                UIMessageTip.ShowError(res.Msg);
                LogExtension.ShowMessage(res.Msg, Microsoft.Extensions.Logging.LogLevel.Error);
            }
        }

        /// <summary>
        /// 展示所选配方内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="index"></param>
        private async void dgv_Recipe_SelectIndexChange(object sender, int index)
        {
            int ID = this.dgv_Recipe.Rows[index].Cells["Id"].Value.ToString().ToInt();
            BaseResult<RecipeQuaeryResultDto> res = await _recipeManager.GetRecipeListByIdAsyncManager(new RecipeQuaeryResultByIdDto() { Id = ID });
            if (res.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                foreach (var item in this.uiTitlePanel1.Controls)
                {
                    if (item is UserSetValue usv)
                    {
                        //通过addDto ，反射至自定义控件属性 VariableName
                        //string text = usv.VariableName;
                        var value = res.Data[0].GetType().GetProperty(usv.VariableName).GetValue(res.Data[0]);
                        usv.VarValue = value.ToString();
                    }
                }
                this.txt_ProductType.Text = res.Data[0].产品类型;
            }
        }

        private async void btn_UpdateRecipe_Click(object sender, EventArgs e)
        {
            if (this.dgv_Recipe.CurrentCell == null)
            {
                UIMessageTip.ShowWarning("请选择修改的配方！");
                return;
            }
            if (this.txt_ProductType.Text == null)
            {
                UIMessageTip.ShowWarning("产品类型不能为空");
                return;
            }

            int id = this.dgv_Recipe.CurrentRow.Cells["Id"].Value.ToString().ToInt();
            RecipeUpdateDto updateDto = new RecipeUpdateDto()
            {
                Id = id,
                产品类型 = this.txt_ProductType.Text
            };
            foreach (var item in this.uiTitlePanel1.Controls)
            {
                if (item is UserSetValue usv)
                {
                    updateDto.GetType().GetProperty(usv.VariableName).SetValue(updateDto, usv.VarValue);
                }
            }
            BaseResult res = await _recipeManager.UpdateRecipeAsyncManager(updateDto);
            if (res.ResultStatus == SystemEnums.ResultStatus.Success)
            {
                UIMessageTip.ShowOk("配方更新完成");
            }
            else
            {
                UIMessageTip.ShowError(res.Msg);
                LogExtension.ShowMessage(res.Msg, Microsoft.Extensions.Logging.LogLevel.Error);
            }
        }

        private async void btn_QueryRecipe_Click(object sender, EventArgs e)
        {
            await LoadRecipe();
        }

        private void btn_ExportRecipe_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel files(*.xlsx)|*.xlsx";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    List<RecipeQuaeryResultDto>? rows = this.dgv_Recipe.DataSource as List<RecipeQuaeryResultDto>;
                    string fileName = saveFileDialog.FileName;
                    MiniExcel.SaveAs(fileName, rows);
                    UIMessageTip.ShowOk("导出成功");
                }
                catch (Exception ex)
                {
                    UIMessageTip.ShowWarning("导出失败");
                    LogExtension.ShowMessage(ex.Message, Microsoft.Extensions.Logging.LogLevel.Error);
                }
            }
        }

        private async void btn_ImportRecipe_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Excel files(*.xlsx)|*.xlsx";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    var filePath = openFileDialog.FileName;
                    List<RecipeQuaeryResultDto> rows = MiniExcel.Query<RecipeQuaeryResultDto>(filePath).ToList();

                    BaseResult<RecipeQuaeryResultDto> res = await _recipeManager.GetRecipeListAsyncManager();
                    if (res.ResultStatus == SystemEnums.ResultStatus.Success)
                    {
                        var dbRows = res.Data;
                        foreach (var row in rows)
                        {
                            RecipeQuaeryResultDto? dbRow = dbRows.FirstOrDefault(x => x.产品类型 == row.产品类型);
                            if (dbRow != null)
                            {
                                //更新
                                RecipeUpdateDto updateDto = row.Adapt<RecipeUpdateDto>();
                                BaseResult resUpdate = await _recipeManager.UpdateRecipeAsyncManager(updateDto);
                                if (resUpdate.ResultStatus == SystemEnums.ResultStatus.Fail)
                                {
                                    UIMessageTip.ShowWarning($"{updateDto.产品类型}-更新失败-" + resUpdate.Msg);
                                    return;
                                }
                            }
                            else
                            {
                                //插入
                                RecipeAddDto recipeAddDto = row.Adapt<RecipeAddDto>();
                                BaseResult resAdd = await _recipeManager.AddRecipeAsyncManager(recipeAddDto);
                                if (resAdd.ResultStatus == SystemEnums.ResultStatus.Fail)
                                {
                                    UIMessageTip.ShowWarning($"{recipeAddDto.产品类型}-添加失败-" + resAdd.Msg);
                                    return;
                                }
                            }
                        }
                        UIMessageTip.ShowOk("导入成功！");
                        await LoadRecipe();
                    }
                    else
                    {
                        UIMessageTip.ShowWarning("导入失败");
                    }
                    /* //查询数据库配方，如果导入配方不存在，即插入；存在则更新
                     for (int i = 0; i < rows.Count; i++)
                     {

                         //统一按照新增走，Failed 切换更新
                         BaseResult res = await _recipeManager.AddRecipeAsyncManager(rows[i].Adapt<RecipeAddDto>());
                         if (res.ResultStatus == SystemEnums.ResultStatus.Success)
                         {
                             continue;
                         }
                         else
                         {
                             await _recipeManager.UpdateRecipeAsyncManager(rows[i].Adapt<RecipeUpdateDto>());
                         }
                     }*/
                }
                catch (Exception ex)
                {

                    UIMessageTip.ShowError("导入失败" + ex.Message);
                    LogExtension.ShowMessage(ex.Message, Microsoft.Extensions.Logging.LogLevel.Error);
                }
            }
        }

        private void btn_DownloadRecipe_Click(object sender, EventArgs e)
        {
            //下载到PLC
            if (!Globals.SiemensClient.Connected)
            {
                UIMessageTip.ShowWarning("请先连接西门子客户端");
                return;
            }
            var res = UIMessageBox.ShowAsk("是否要下载到PLC？");
            if (res)
            {
                foreach (var item in this.uiTitlePanel1.Controls)
                {
                    if (item is UserSetValue usv)
                    {
                        if(usv.VarValue == string.Empty)
                        {
                            usv.VarValue = "0";
                        }
                        if (!Globals.PLCWrite(usv.VariableName, usv.VarValue,DataTypeEnum.Float))
                        {
                            //此处变量类型单一，统一用float，若有其他类型，可做判断
                            new UIMessageForm().ShowErrorDialog($"{usv.VariableName}下载失败");
                            return;
                        }
                    }
                }
                UIMessageTip.ShowOk("下载成功");
            }
        }
        #region 窗体切换卡顿
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams paras = base.CreateParams;
                paras.ExStyle |= 0x02000000;
                return paras;
            }
        }
        #endregion
    }
}
